<?php

namespace app\admin\model;

use think\Model;
use think\facade\Config;
use app\admin\validate\AuthGroup as ModelValidate;
class AuthGroup extends Model{
  public function group_accesses(){
    return $this->hasMany('GroupAccess', 'group_id');
  }

  /**
   * 保存方法
   * @Author   zhanghong
   * @DateTime 2018-03-04
   * @param    array      $data 保存数据
   * @param    array      $opts 辅助信息
   * @return   array
   */
  public function saveItem($data, $opts = []){
    $res = ['status' => false, 'msg' => "保存失败"];
    if(!is_array($data)){
      $res['msg'] = '保存数据格式不正确';
    }

    if(isset($opts['id']) && $opts['id'] > 0){
      $data['id'] = $opts['id'];
    }

    $validate = new ModelValidate();
    if(!$validate->check($data)){
      $res['msg'] = $validate->getError();
      return $res;
    }

    if(isset($data['id'])){
      $this->isUpdate(true)->save($data);
      $id = $data['id'];
      $msg = '更新成功';
    }else{
      $this->isUpdate(false)->save($data);
      $id = $this->id;
      $msg = '添加成功';
    }
    $res = ['status' => true, 'msg' => $msg];
    if(isset($opts['is_return']) && $opts['is_return']){
      $res['data'] = $this->where('id', $id)->find();
    }
    return $res;
  }

  /**
   * 删除记录
   * @Author   zhanghong
   * @DateTime 2018-03-04
   * @param    integer    $id 删除元素主键
   * @return   array
   */
  public function deleteItem($id){
    $res = ['status' => false, 'msg' => "删除失败"];
    if(!is_numeric($id)){
      $res['msg'] = '删除参数错误';
      return $res;
    }

    $item = $this->where('id', $id)->find();
    if(empty($item)){
      $res['msg'] = "删除记录不存在";
      return $res;
    }

    $access_count = $item->group_accesses()->count();
    if($access_count){
      $res['msg'] = '拥有Access关联记录对象不能删除';
      return $res;
    }

    $item->delete();

    $res = ['status' => true, 'msg' => '删除成功'];
    return $res;
  }

  /**
   * 查询访问
   * @Author zhanghong
   * @Date   2017-01-06
   * @param  string     $group_type  群组类型
   * @param  array      $param      查询参数
   * @param  integer    $list_rows  每页显示的记录数量
   * @return Paginate
   */
  public function adminPaginate($group_type, $param, $list_rows = NULL){
    if(!is_array($param)){
      $param = [];
    }
    $param['group_type'] = $group_type;
    $map = $this->mapSearchParam($param);

    // order string
    if(isset($param['sort'])){
      $order_type = $param['sort'];
    }else{
      $order_type = 'default';
    }
    $order_str = $this->orderStr($order_type);

    if(empty($list_rows)){
      $list_rows = Config::get('app.paginate.list_rows');
    }

    $config = ['query' => $param];
    // 分页参数名是page ，paginate方法内有获取到该值的方法
    $page = 1;
    if(isset($param['page'])){
      $page = intval($param['page']);
    }
    $config['page'] = $page;
    $paginate = $this->where($map)->order($order_str)->paginate($list_rows, false, $config);
    return $paginate;
  }

  /**
   * 单个类型的所有auth_group
   * @Author zhanghong
   * @Date   2017-01-06
   * @param  string     $group_type  群组类型
   * @param  boolean    $only_active 是否只返回active记录
   * @return array                   AuthGroup List
   */
  public function selectTypeAll($group_type, $only_active = true){
    $param = ['only_active' => $only_active, 'group_type' => $group_type];
    $map = $this->mapSearchParam($param);

    $order_str = $this->orderStr('default');

    return $this->where($map)->order($order_str)->select();
  }

  // /**
  //  * 用户所在组
  //  * @Author zhanghong
  //  * @Date   2017-01-01
  //  * @param  integer     $user_id 用户ID
  //  * @return array                AuthGroup
  //  */
  // public function userGroup($user_id){
  //   $prefix = Config::get("database.prefix");
  //   $group = $this->alias('g')->join("{$prefix}group_access a", "g.id=a.group_id")
  //                 ->where("a.uid", $user_id)->find();
  //   return $group;
  // }

  /**
   * 验证输入的AuthGroup Title是否唯一（因为Validate的带条件查询有问题，不能使用）
   * @Author zhanghong
   * @Date   2017-01-05
   * @param  array      $data  输入数据
   * @return boolean
   */
  public function uniqueTitle($data){
    $param = [
      'status' => 1,
    ];
    $param_field = ['title', 'group_type', 'id'];
    foreach ($param_field as $key => $name) {
      if(!isset($data[$name])){
        continue;
      }
      if($name == 'id'){
        $param_key = 'id_neq';
      }else{
        $param_key = $name;
      }
      $param[$param_key] = $data[$name];
    }
    $map = $this->mapSearchParam($param);
    if($this->where($map)->count()){
      return false;
    }
    return true;
  }


  /**
   * 排序方式
   * @Author   zhanghong
   * @DateTime 2018-03-04
   * @param    string     $order_type 排序类型
   * @return   string
   */
  private function orderStr($order_type = 'default'){
    switch ($order_type) {
    default:
      $order_str = 'sort ASC, id DESC';
      break;
    }

    return $order_str;
  }

  /**
   * 把请求参数转化成查询条件
   * @Author   zhanghong
   * @DateTime 2018-03-04
   * @param    [type]     $param [description]
   * @return   [type]            [description]
   */
  protected function mapSearchParam($param){
    $map = [];
    foreach ($param as $key => $value) {
      if(!is_array($value)){
        $value = trim($value);
      }
      switch ($key) {
      case 'keyword':
        if(empty($value)){
          continue;
        }else{
          $keyword = "%{$value}%";
        }
        $map['title'] = ['title', 'like', $keyword];
        break;
      case 'only_active':
        $map['status'] = ['status', '=', true];
        break;
      case 'status':
        if(!is_null($value)){
          $value = (bool)$value;
          $map[$key] = [$key, '=', $value];
        }
        break;
      case 'id':
        if(!is_null($value)){
          $value = intval($value);
          $map[$key] = [$key, '=', $value];
        }
        break;
      case 'id_neq':
        if(!is_null($value)){
          $value = intval($value);
          $map['id'] = ['id', '<>', $value];
        }
        break;
      case 'title':
      case 'group_type':
        if(!empty($value)){
          $map[$key] = [$key, '=', $value];
        }
        break;
      }
    }
    return $map;
  }
}
